package controllers

import (
	"io"
	"net/http"
	"os"

	"github.com/gin-gonic/gin"
)

func Upload(c *gin.Context) {
	c.Request.ParseMultipartForm(1024 * 1024 * 1024 * 2)
	file, handler, err := c.Request.FormFile("uploadfile")
	if err != nil {
		handleErr(c, err.Error())
		return
	}
	out, err := os.Create("files/" + handler.Filename)
	if err != nil {
		handleErr(c, err.Error())
		return
	}
	defer out.Close()
	io.Copy(out, file)
	handleOk(c, "上传文件成功")
}

func FileIndex(c *gin.Context) {
	c.Header("Content-Type", "text/html; charset=utf-8")
	str := `
<!DOCTYPE html>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
	<title>文件</title>
</head>
<body>
	<div>
		<a href="/file/upload">上传文件</a></p>
		<a href="/files">查看文件</a></p>
	</div>
</body>
</html>
	`
	c.String(http.StatusOK, str)
}

func UploadIndex(c *gin.Context) {
	c.Header("Content-Type", "text/html; charset=utf-8")
	str := `
<html>
<head>
    <title>上传文件</title>
</head>
<body>
<form enctype="multipart/form-data" action="/file/upload" method="post">
  <input type="file" name="uploadfile" />
  <input type="submit" value="upload" />
</form>
</body>
</html>
	`
	c.String(http.StatusOK, str)
}
